#pragma
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<cstring>
#include<cstdlib>
#include<cerrno>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>

namespace server{
    static const string defaultIp="0.0.0.0";
    enum{USAGE_ERR=1,SOCKET_ERR,BIND_ERR};
    class udpserver{
        public:
            udpserver(const uint16_t &port,const string ip=defaultIp)
            :_port(port)
            ,_ip(ip)
            {}
            void init()
            {
                _sockFd=socket(AF_INET,SOCK_DGRAM,0);
                if(_sockFd<0)
                {
                   cerr<<"socket error: "<<errno<<":"<<strerror(errno)<<endl;
                    exit(SOCKET_ERR);
                }
        
        
                struct sockaddr_in local;
                bzero(&local,sizeof(local));
        
        
                local.sin_family=AF_INET;
                local.sin_port=htons(_port);
                local.sin_addr.s_addr=_ip.empty()?htonl(INADDR_ANY):inet_addr(_ip.c_str());
        
        
                if(bind(_sockFd,(const struct sockaddr*)&local,sizeof(local))==-1){
                    cerr<<"bind error"<<errno<<":"<<strerror(errno)<<endl;
                    exit(BIND_ERR);
                }
            }
        
            void start(){
                for(;;)
                {
                    sleep(1);
                }
            }
            ~udpserver()
            {}

        private:
            uint16_t _port;
            string _ip;
            int _sockFd;
    }
}